package com.aliengen.thingple.thingple.fillingstation;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.aliengen.thingple.thingple.AbstractThingpleActivity;
import com.aliengen.thingple.thingple.DialogRFIDReadingFragment;
import com.aliengen.thingple.thingple.R;
import com.aliengen.thingple.thingple.tag.BundleTag;
import com.aliengen.thingple.thingple.tag.CylinderTag;
import com.aliengen.thingple.thingple.tag.Tag;
import com.aliengen.thingple.thingple.tag.exception.InvalidTagException;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
public class SingleReadActivity extends AbstractThingpleActivity implements DialogRFIDReadingFragment.ReadingDialogListener {
    DialogRFIDReadingFragment dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_single_read);
        setOperatorName();

        dialog = new DialogRFIDReadingFragment();
        dialog.init(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mApplication.getHandler().setOnEventListener(null);
    }

    public void onClickReadCylinder(View view){dialog.startReading(); }

    public Tag getTagFromBytes(byte[] tag) throws InvalidTagException
    {
        Tag t;
        try
        {
            t = new CylinderTag(tag);
        } catch(InvalidTagException e)
        {
            try
            {
                t = new BundleTag(tag);
            }catch(InvalidTagException f)
            {
                throw f;
            }
        }
        return t;
    }

    public void onReadingNew(Tag tag) {
        if(tag instanceof CylinderTag) {
            Intent nextScreen = new Intent(getApplicationContext(), CylinderActivity.class);
            nextScreen.putExtra("cylinder_tag", tag);
            startActivity(nextScreen);
            this.finish();
        }
        else
        {
            Intent nextScreen = new Intent(getApplicationContext(), BundleActivity.class);
            nextScreen.putExtra("bundle_tag", tag);
            startActivity(nextScreen);
            this.finish();
        }
    }
}
